<template>
    <div>
        <div class="layout-main-hd">
            <div class="mod-act-panel">
                <div class="act-panel-inner clearfix">
                    <div class="mod-action-wrap mod-action-wrap-c mod-action-wrap-d  mod-action-wrap-mode clearfix">
                        <div class="action-item">
                            <div class="action-item-con">
                                <i class="icon icon-mode-list"></i>
                                <span class="act-txt">列表</span>
                            </div>
                        </div>
                        <div class="action-item act">
                            <div class="action-item-con">
                                <i class="icon icon-mode-thumb"></i>
                                <span class="act-txt">缩略图</span>
                            </div>
                        </div>
                    </div>
                    <div class="mod-breadcrumb">
                        <ul class="breadcrumb clearfix">
                            <li class="item all" v-for="(item, index) in breadcrumb" :class="(index+1)==breadcrumb.length?'cur':''">
                                <i class="icon icon-bread-next" v-if="index>0&&index<=breadcrumb.length"></i>
                                <router-link :to="item.dir_name == '/' ? '/disk':'/disk/dir/'+item.id">
                                    <i class="icon"></i>{{ item.dir_name == '/' ? '全部' : item.dir_name }}
                                </router-link>
                            </li>
                        </ul>
                    </div>
                </div>
            </div>
        </div>
        <div class="layout-main-bd">
            <div class="mod-loadmore load" v-if="pageLoding">
                <i class="icon icon-load-bullet-left"></i>
                <i class="icon icon-load-bullet"></i>
                <i class="icon icon-load-bullet-right"></i>
            </div>

            <div class="mod-status" v-else-if="dirList.length < 1 && fileList.length < 1">
                <div class="empty-box">
                    <div class="status-inner">
                        <i class="icon icon-nofile"></i>
                        <h2 class="title">暂无文件</h2>
                        <p class="txt">请点击左上角的“上传”按钮添加</p>
                    </div>
                </div>
            </div>
            <div v-else-if="dirList.length > 0 || fileList.length > 0">
                <div id="container-group" class="mod-list-group mod-list-group-thumb" @click="cleanSelectData"  @keydown.ctrl.65.stop="selectAll($event)" @keydown.meta.65.stop="selectAll($event)">
                    <div class="list-group-hd" style="">
                        <div class="list-group-tit-wrap">
                            <div class="list-group-tit name cur " :class="selectedData.length > 0 ? 'checked' : ''">
                                <span class="mod-check"  :class="selectedData.length == Bus.Batch.AllData.length ? 'act' : ''">
                                    <i class="icon icon-check-s icon-checkbox" @click.stop="selectedData.length == Bus.Batch.AllData.length ? selectedData = [] : selectedData = Bus.Batch.AllData"></i>
                                    <span class="check-info" v-if="selectedData.length > 0">已选择<b class="check-info-num">{{ selectedData.length }}</b>项</span>
                                </span>
                                <span class="tit-con" >修改时间<i class="icon icon-sort"></i></span>
                                <div class="mod-bubble-menu with-border">
                                    <ul>
                                        <li class="menu-item">
                                            <span class="txt">
                                                <i class="icon icon-sel"></i>升序
                                            </span>
                                        </li>
                                        <li class="menu-item act">
                                            <span class="txt">
                                                <i class="icon icon-sel"></i>降序
                                            </span>
                                            <div class="spliter"></div>
                                        </li>
                                        <li class="menu-item">
                                            <span class="txt">
                                                <i class="icon icon-sel"></i>文件名
                                            </span>
                                        </li>
                                        <li class="menu-item act">
                                            <span class="txt">
                                                <i class="icon icon-sel"></i>修改时间
                                            </span>
                                        </li>
                                    </ul>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div tabindex="0" class="list-group-bd" selectbox-id="4" dragdrop-id="2" scroll-bottom-id="4">
                        <div class="mod-item-list">
                            <ul class="item-list clearfix">
                                <li class="item" v-for="item in dirList" style="width: 116.75px;" @contextmenu.prevent.stop="$refs.dirCtx.open($event, item)" :class="is_selected(item.id, item.type) ? 'act' : ''" :data-id="item.id" data-type="dir">
                                    <div class="inner">
                                        <i class="icon-wrapper">
                                            <i class="icon icon-file-l"></i>
                                        </i>
                                        <span :title="item.dir_name" class="txt" style="">
                                            <input v-if="item.edit" type="text" class="ui-input" v-model="selectedData[0].newVal" @click.stop="return false;">
                                            <span v-else>{{ item.dir_name }}</span>
                                        </span>
                                    </div>
                                    <i class="icon icon-check-s icon-checkbox" @click.stop="pushData(item)"></i>
                                </li>
                            </ul>
                        </div>
                        <div class="mod-figure-list">
                            <div class="figure-box clearfix">
                                <ul class="figures-list clearfix">
                                    <li class="figure-list-item" v-for="item in fileList" style="width: 154.667px;"  @contextmenu.prevent.stop="$refs.fileCtx.open($event, item)" @click="toDir(item.id)" :class="is_selected(item.id, item.type) ? 'act' : ''" :data-id="item.id" data-type="file">
                                        <div class="figure-list-item-inner">
                                            <i class="icon icon-check-s icon-checkbox"></i>
                                            <div class="figure-list-item-pic" style="height: 154.667px;">
                                                <div class="img-wrapper">
                                                    <i class="icon icon-l icon-zip-l"></i>
                                                </div>
                                            </div>
                                            <div class="figure-list-item-txt">
                                                <p class="tit">
                                                    <span :title="item.file_name" class="txt">{{ item.file_name }}</span>
                                                </p>
                                            </div>
                                        </div>
                                    </li>
                                </ul>
                            </div>
                        </div>
                        <div class="mod-loadmore" v-show="loadMoreLoding">
                            <i class="icon icon-load-bullet-left"></i>
                            <i class="icon icon-load-bullet"></i>
                            <i class="icon icon-load-bullet-right"></i>
                        </div>

                        <div class="list-group-info" v-if="(dirList.length + fileList.length) == allCount">
                            <p class="info-con">共<b class="count">{{ dirList.length + fileList.length }}</b>项</p>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!--重命名-->
        <a-modal
                v-model="EditModal"
                :closable="false"
                wrapClassName="edit_item_modal"
                :width="400"
        >
            <p class="title">重命名</p>
            <p class="input">
                <a-form :form="ReNameForm">
                    <a-form-item>
                        <a-input
                                v-decorator="['name',{rules: [{ validator: this.handleNameValidate }], validateTrigger: ['change', 'blur']}]"
                                :placeholder="'请输入'+reNameTitle +'名称'" />
                    </a-form-item>
                </a-form>
            </p>

            <template slot="footer">
                <a-button @click="selectedData=[],EditModal=false">取 消</a-button>
                <a-button htmlType="submit" type="primary" @click.stop.prevent="saveEditItem" :loading="EditLoding">保 存</a-button>
            </template>
        </a-modal>

        <!--删除-->
        <a-modal
                v-model="DeleteModal"
                :closable="false"
                wrapClassName="delete_item_modal"
                :width="416"
        >
            <template slot="footer">
                <a-button @click="DeleteModal=false">取 消</a-button>
                <a-button type="danger" :loading="DeleteLoding" @click="deleteAct">确 定</a-button>
            </template>
            <p>
                <a-icon type="question-circle" size="22" />
                <span class="ant-modal-confirm-title">{{ DeleteTitle }}</span>
            </p>
            <div class="ant-modal-confirm-content">{{ DeleteContent }}</div>
        </a-modal>


        <context-menu id="dirCtx" ref="dirCtx" @ctx-open="onCtxOpen" @ctx-cancel="resetCtxLocals" @ctx-close="onCtxClose">
            <!--<li class="ctx-header">下载</li>-->
            <li class="ctx-item" @click.stop="toDir(menuData.id)">打开</li>
            <li class="ctx-item">分享</li>
            <!--<li class="ctx-item">收集文件</li>-->
            <li class="ctx-item">移动到</li>
            <li class="ctx-item">复制到</li>
            <li class="ctx-item" @click="editItemName(menuData,'folder')">重命名</li>
            <li class="ctx-item">移入保险箱</li>
            <div class="spliter"></div>
            <li class="ctx-item" @click="deleteItem(menuData,'dir')">删除</li>
            <!--<li class="ctx-item disabled">收集文件</li>-->
            <!--<li class="ctx-item" @click="logClick($event, menuData)">add to log</li>-->
        </context-menu>

        <context-menu id="fileCtx" ref="fileCtx" @ctx-open="onCtxOpen" @ctx-cancel="resetCtxLocals" @ctx-close="onCtxClose">
            <li class="ctx-header">下载</li>
            <li class="ctx-item">分享</li>
            <!--<li class="ctx-item">收集文件</li>-->
            <li class="ctx-item">移动到</li>
            <li class="ctx-item">复制到</li>
            <li class="ctx-item" @click="editItemName(menuData,'folder')">重命名</li>
            <li class="ctx-item">移入保险箱</li>
            <div class="spliter"></div>
            <li class="ctx-item" @click="deleteItem(menuData,'file')">删除</li>
        </context-menu>


    </div>
</template>

<script>
    import { array_merge } from "../../utils/utils";
    import ApiUrl from '../../config/api'

    export default {
        name: "layout-main",
        data() {
            return {
                trashList: [],
                dirList: [],
                fileList: [],
                selectedData: [],
                breadcrumb: [],
                allCount: 0,
                reNameTitle: '',
                EditLoding: false,
                EditModal: false,
                DeleteLoding: false,
                DeleteModal: false,
                DeleteTitle: '',
                DeleteContent: '',
                pageLoding: false,
                loadMoreLoding: false,
                dirId: '',
                colors: ['pink', 'lightblue', 'green', 'red', 'turquoise'],
                showCtx: false,
                menuData: {},
                ReNameForm: this.$form.createForm(this,{props:{}}),
                contextClicks: []
            }
        },
        created: function () {
            let tokenStr = 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1aWQiOjEsIm5pY2tuYW1lIjoiMTA2MDIxNjAzNkBxcS5jb20iLCJ0cnVlbmFtZSI6bnVsbCwiZW1haWwiOiIxMDYwMjE2MDM2QHFxLmNvbSIsImF2YXRhciI6Ilwvc3RhdGljXC9pbWFnZXNcL2F2YXRhci5wbmciLCJ1c2VkX3N0b3JhZ2UiOjAsInVzZXJfZ3JvdXAiOjEsInN0YXR1cyI6MSwiaWF0IjoxNTQ3MDg5OTEyLCJleHBpcmVzX2luIjo3MjAwfQ.zLC4aoiEKBj3BCewD2J6cBpdjuBmM8M99rx6TdTwH_w';
            window.localStorage.setItem('token',tokenStr);
            this.pageLoad()
        },
        watch: {
            '$route': 'pageLoad',
            selectedData (newVal, oldVal) {
                this.Bus.Batch.selectedData = newVal;
            },
            dirList (newVal, oldVal) {
                this.Bus.Batch.dirList = newVal;
            },
            fileList (newVal, oldVal) {
                this.Bus.Batch.fileList = newVal;
            },
            BusAllData (val) {

            },
            BusSelectedData (val) {
                this.selectedData = val;
            },
        },
        computed: {
            BusAllData() {
                return this.Bus.Batch.AllData;
            },
            BusSelectedData() {
                return this.Bus.Batch.selectedData;
            }
        },
        methods: {
            pageLoad() {
                this.getList('page');
            },
            loadMore() {
                this.getList('more');
            },
            setLoding(type,status) {
                let st = status == 1 ? true : false;
                if(type == 'page') {
                    this.pageLoding = st;
                    this.Bus.disk.pageLoding = st;
                }else if(type == 'more'){
                    this.loadMoreLoding = st;
                    this.Bus.disk.loadMoreLoding = st;
                }
            },
            getList(type) {
                let dirId = typeof this.$route.params.dir_id == "undefined" ? '':this.$route.params.dir_id;
                this.dirId = dirId;
                this.setLoding(type,1);
                this.$ajax.get(ApiUrl.BatchApiUrl.BatchTrash, {}, {}).then(function (ret) {
                    let dataS = ret.data;
                    let data = dataS.data;
                    if (dataS.code == 200) {
                        this.trashList = data.data;
                        this.Bus.Batch.AllData = array_merge(this.dirList, this.fileList);
                        this.allCount = data.count;
                    } else {
                        if(dataS.code == 404) {
                            this.$router.push('/disk');
                        }
                    }
                    this.setLoding(type,0);
                }.bind(this));
            },
            editItemName(item,type) {
                let EditItem = item;
                this.EditLoding=false;
                this.EditModal=true;
                EditItem.edit_type = 'folder';
                EditItem.oldVal = type == 'folder' ? item.dir_name : item.file_name;
                EditItem.newVal = EditItem.oldVal;
                EditItem.modalTitle = type == 'folder' ? '文件夹' : '文件';
                this.selectedData.push(EditItem);
                this.reNameTitle = EditItem.modalTitle;
                this.Bus.disk.editItemNameData = EditItem;
                setTimeout(function () {
                    this.ReNameForm.setFieldsValue({
                        name: EditItem.newVal
                    });
                }.bind(this),20)
            },
            handleNameValidate(rule, value, callback) {
                value = typeof value != "undefined" ? value : '';
                let megTitle = this.selectedData[0].edit_type == 'folder' ? '文件夹' : '文件';
                const regex = new RegExp("[:*?/\\\"<>|']", 'g');
                if(value == "" || value.replace(/^\s+|\s+$/g, '') == ''){
                    callback(new Error('请输入'+megTitle+'名称'));
                }else if(regex.test(value)){
                    callback(new Error(megTitle+'名称不能包含以下字符之一：:*?/"<>|\\'));
                }
                this.selectedData[0].newVal = value;
                callback();
            },
            deleteItem(item,type) {
                /*let is_selected = this.is_selected(item.id, type);
                if(is_selected == false) {
                    this.selectedData = [];
                }*/

                let datas = this.selectedData;
                let DirCount = 0, FileCount = 0,deleteArr = [];
                for (let item of datas) {
                    if(item.type == 'dir') {
                        DirCount++;
                    } else if(item.type == 'file') {
                        FileCount++;
                    }

                    /*if(parseInt(item.id) > 0 && (item.type == 'dir' || item.type == 'file')) {
                        let deleteItem = {
                            id: item.id,
                            type: item.type
                        }
                        deleteArr.push(deleteItem);
                    }*/
                }

                let data = {
                    id: item.id,
                    type: item.type
                };
                // deleteArr.push(data);
                // console.log(this.selectedData);
                var title = '你确定要删除这';
                let title2 = DirCount > 1 || FileCount > 1 ? '些' : '个';
                let title3 = DirCount > 0 && FileCount > 0 ? '文件（夹）' : DirCount > 0 && FileCount == 0 ? '文件夹' : '文件';
                let Title = title+title2+title3+'吗？';

                // this.selectedData = deleteArr;
                this.DeleteTitle = '删除'+title3;
                this.DeleteContent = Title;
                this.DeleteModal = true;
            },
            deleteAct() {
                if(this.selectedData.length < 1 || this.DeleteLoding) {
                    return false;
                }
                let hide = this.$message.loading('正在删除...', 0);
                this.DeleteModal = false;
                // this.DeleteLoding = true;
                let Url = ApiUrl.BatchApiUrl.Delete;
                this.$ajax.delete(Url, this.selectedData, {}).then(function (ret) {
                    let dataS = ret.data;
                    this.$message.destroy();
                    if (dataS.code == 200) {
                        this.DeleteLoding = false;
                        this.selectedData = [];
                        this.DeleteModal = false;
                        this.$message.success('删除成功');
                    } else {
                        this.DeleteLoding = false;
                        this.selectedData = [];
                        this.DeleteModal = false;
                        let msg = dataS.msg || '删除失败';
                        this.$message.error(msg);
                    }
                    this.DeleteLoding = false;
                    this.pageLoad();
                }.bind(this));
            },
            is_selected(id, type) {
                for (let item of this.selectedData) {
                    if(item.id == id && item.type == type) {
                        return true;
                    }
                }
                return false;
            },
            pushData(data) {
                let newVal=[],is_selece=false;
                for (let item of this.selectedData) {
                    if(item.id == data.id) {
                        is_selece = true;
                    } else {
                        newVal.push(item);
                    }
                }

                if(is_selece == false) {
                    newVal.push(data);
                }
                this.selectedData = newVal;
            },
            selectAll($event) {
                let datas = array_merge(this.dirList,this.fileList);
                this.selectedData = datas;
                $event.preventDefault();
                return false;
            },
            cleanSelectData() {
                this.selectedData = [];
            },
            saveEditItem() {
                this.ReNameForm.validateFields((err, values) => {
                    if (!err) {
                        this.EditLoding = true;
                        if(values.name == this.selectedData[0].oldVal) {
                            this.$message.success('保存成功');
                            setTimeout(function () {
                                this.EditLoding = false;
                                this.selectedData = [];
                                this.EditModal = false;
                            }.bind(this),500);
                            return false;
                        }
                        let Url = ApiUrl.BatchApiUrl.ReName;
                        this.$ajax.put(Url, {re_name:values.name,id:this.selectedData[0].id,type:this.selectedData[0].edit_type}, {}).then(function (ret) {
                            let dataS = ret.data;
                            if (dataS.code == 200) {

                                if(this.selectedData[0].edit_type == 'folder') {
                                    for (let item of this.dirList) {
                                        if(item.id == this.selectedData[0].id) {
                                            item.dir_name = values.name
                                        }
                                    }
                                } else {
                                    for (let item of this.fileList) {
                                        if(item.id == this.selectedData[0].id) {
                                            item.dir_name = values.name
                                        }
                                    }
                                }

                                this.EditLoding = false;
                                this.selectedData = [];
                                this.EditModal = false;
                                this.$message.success('修改成功');
                            } else {
                                this.EditLoding = false;
                                this.selectedData = [];
                                this.EditModal = false;
                                let msg = dataS.msg || '保存失败';
                                this.$message.error(msg);
                            }
                            this.EditLoding = false;
                        }.bind(this));
                    }else{
                        // console.log('error',values);
                    }
                });
            },



            onCtxOpen(item) {
                let dirCtxDom = document.getElementById('dirCtx');
                let fileCtxDom = document.getElementById('fileCtx');
                let pageCtxDom = document.getElementById('pageCtx');
                if(item.type == 'dir') {
                    dirCtxDom.style.cssText = 'display:block';
                }else{
                    fileCtxDom.style.cssText = 'display:block';
                }
                pageCtxDom.style.cssText = 'display:none';

                let is_selected = this.is_selected(item.id, item.type);
                if(!is_selected) {
                    this.selectedData = [];
                    this.selectedData.push(item);
                }
                this.menuData = item;
            },
            onCtxClose(locals) {
                // this.menuData = {};
                // this.selectedData = [];
                console.log('close', locals)
            },
            resetCtxLocals() {
                this.menuData = {};
                this.selectedData = [];
            },
            logClick(e,context) {
                console.log(e,context);
            },
        }
    }

    function logger(n) {
        let name = 'event:ctx-' + n
        return function(...more) {
            console.log(name, ...more)
        }
    }
</script>

<style scoped lang="less">
    @import "../../assets/css/main.less";
</style>
<style lang="less">
    .edit_item_modal {
        .title {
            text-align: center;
            color: #333;
            font-size: 18px;
            line-height: 26px;
            min-height: 14px;
        }
        .input {
            text-align: center;
            margin-top: 20px;
        }
        .ant-modal-content {
            .ant-modal-body {
                padding: 24px 24px 0 24px;
            }
        }
    }
    .delete_item_modal {
        .ant-modal-body {
            padding: 32px 32px 24px;
        }
        .anticon-question-circle {
            color: #faad14;
            font-size: 22px;
            margin-right: 16px;
            float: left;
        }
        .ant-modal-confirm-title {
            color: rgba(0,0,0,.85);
            font-weight: 500;
            font-size: 16px;
            line-height: 1.4;
            display: block;
            overflow: hidden;
        }
        .ant-modal-confirm-content {
            margin-left: 38px;
            font-size: 14px;
            color: rgba(0,0,0,.65);
            margin-top: 8px;
        }
        .ant-modal-footer {
            border: none;
            padding: 20px 30px;
        }
    }
</style>